// LoginServlet.java
package controller;

import dao.UserDAO;
import model.User;

//import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//@WebServlet(name = "LoginServlet", value = "/login")
//@WebServlet("/login")
//public class LoginServlet extends HttpServlet {
//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response)
//            throws IOException {
//
//        response.setContentType("application/json");
//        response.setCharacterEncoding("UTF-8");
//
//        String email = request.getParameter("email");
//        String password = request.getParameter("password");
//
//        UserDAO userDAO = new UserDAO();
//        User user = userDAO.validateUser(email, password);
//
//        try (PrintWriter out = response.getWriter()) {
//            if (user != null) {
//                out.print(String.format(
//                        "{\"success\": true, \"user\": {\"id\": %d, \"username\": \"%s\", \"email\": \"%s\"}}",
//                        user.getId(),
//                        user.getUsername() != null ? user.getUsername() : "",
//                        user.getEmail() != null ? user.getEmail() : ""
//                ));
//            } else {
//                out.print("{\"success\": false, \"message\": \"邮箱或密码错误\"}");
//            }
//        }
//    }
//}

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String username = request.getParameter("username"); // 改为获取username参数
        String password = request.getParameter("password");

        UserDAO userDAO = new UserDAO();
        User user = userDAO.validateUserByUsername(username, password); // 使用新方法

        try (PrintWriter out = response.getWriter()) {
            if (user != null) {
                out.print(String.format(
                        "{\"success\": true, \"user\": {\"id\": %d, \"username\": \"%s\", \"email\": \"%s\"}}",
                        user.getId(),
                        user.getUsername() != null ? user.getUsername() : "",
                        user.getEmail() != null ? user.getEmail() : ""
                ));
            } else {
                out.print("{\"success\": false, \"message\": \"用户名或密码错误\"}"); // 修改错误提示
            }
        }
    }
}